package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Comment;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.service.CommentService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Override
    public List<Comment> getCommentTree(Long postId) {
        // 获取帖子所有评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getPostId, postId)
                .orderByAsc(Comment::getCreatedAt);
        List<Comment> allComments = list(queryWrapper);

        // 构建评论树
        Map<Long, List<Comment>> commentMap = new HashMap<>();
        List<Comment> rootComments = new ArrayList<>();

        // 按父评论ID分组
        for (Comment comment : allComments) {
            if (comment.getParentId() == null) {
                rootComments.add(comment);
            } else {
                commentMap.computeIfAbsent(comment.getParentId(), k -> new ArrayList<>())
                        .add(comment);
            }
        }

        // 递归设置子评论
        rootComments.forEach(root -> setChildren(root, commentMap));

        return rootComments;
    }

    private void setChildren(Comment parent, Map<Long, List<Comment>> commentMap) {
        List<Comment> children = commentMap.get(parent.getId());
        if (children != null) {
            children.forEach(child -> setChildren(child, commentMap));
        }
    }

    @Override
    public boolean addComment(Comment comment) {
        return save(comment);
    }

    @Override
    public boolean deleteComment(Long commentId) {
        // 获取所有子评论ID
        List<Long> commentIds = new ArrayList<>();
        commentIds.add(commentId);
        collectChildrenIds(commentId, commentIds);

        // 批量删除评论
        return removeByIds(commentIds);
    }

    private void collectChildrenIds(Long parentId, List<Long> commentIds) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, parentId);
        List<Comment> children = list(queryWrapper);

        for (Comment child : children) {
            commentIds.add(child.getId());
            collectChildrenIds(child.getId(), commentIds);
        }
    }

    @Override
    public List<Comment> getDirectReplies(Long commentId) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId, commentId)
                .orderByAsc(Comment::getCreatedAt);
        return list(queryWrapper);
    }
}